package com.atom.module.mvvm.extren

import android.view.MenuItem
import android.view.View
import androidx.annotation.CheckResult
import androidx.appcompat.widget.Toolbar
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate

@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
fun Toolbar.itemClicks()= callbackFlow<MenuItem>  {
    checkMainThread()
    val listener = Toolbar.OnMenuItemClickListener {
        trySend(it)
        true
    }
    setOnMenuItemClickListener(listener)
    awaitClose { setOnMenuItemClickListener(null) }
}.conflate()

@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
fun Toolbar.navigationClicks() = callbackFlow<Unit> {
    checkMainThread()
    val listener = View.OnClickListener {
        trySend(Unit)
    }
    setNavigationOnClickListener(listener)
    awaitClose { setNavigationOnClickListener(null) }
}.conflate()